import { useAuthStore } from '@/store/modules/auth';
import { sessionStg } from '@/utils/storage';
import { fetchRefreshToken } from '../api';
import type { RequestInstanceState } from './type';

export function getAuthorization() {
  const token = sessionStg.get('token');
  const Authorization = token ? `Bearer ${token}` : null;

  return Authorization;
}

/** 更新token */
async function handleRefreshToken() {
  const { resetStore, logout } = useAuthStore();
  const rToken = sessionStg.get('refreshToken') || '';
  if (!rToken) {
    logout();
  }
  const { error, data } = await fetchRefreshToken(rToken);

  if (!error) {
    sessionStg.set('token', data.accessToken);
    sessionStg.set('refreshToken', data.refreshToken);
    sessionStg.set('expiration', data.expiration);
    return true;
  }

  resetStore();

  return false;
}

export async function handleExpiredRequest(state: RequestInstanceState) {
  if (!state.refreshTokenFn) {
    state.refreshTokenFn = handleRefreshToken();
  }

  const success = await state.refreshTokenFn;

  setTimeout(() => {
    state.refreshTokenFn = null;
  }, 1000);

  return success;
}

export function showErrorMsg(state: RequestInstanceState, message: string) {
  if (!state.errMsgStack?.length) {
    state.errMsgStack = [];
  }
  const isExist = state.errMsgStack.includes(message);

  if (!isExist) {
    state.errMsgStack.push(message);

    /** 接口调用过快可能导致全局error弹窗还没有挂载成功，轮询执行这一步骤 */
    if (window.$message?.error) {
      showErrorMessage();
    } else {
      const interval = setInterval(() => {
        if (window.$message?.error) {
          clearInterval(interval);
          showErrorMessage();
        }
      }, 20);
    }

    /** 显示错误信息方法 */
    function showErrorMessage() {
      window.$message?.error(message, {
        onLeave: () => {
          state.errMsgStack = state.errMsgStack.filter(msg => msg !== message);
          setTimeout(() => {
            state.errMsgStack = [];
          }, 5000);
        }
      });
    }
  }
}

/**
 * 解析menu中的meta为对象
 *
 * @param routes 原始路由对象
 * @returns 路由对象
 */
export function parseMenuMeta(routes: ManageApi.MenuManage.Menu[]) {
  try {
    routes.forEach(route => {
      if (route.meta) {
        route.meta = JSON.parse(route.meta as unknown as string);
      }
      if (route.children) {
        parseMenuMeta(route.children);
      }
    });
    return routes;
  } catch (error) {
    return new Error(error as string);
  }
}
